package com.richstonedt.smartcity.xaytsccommonrs.handler;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.richstonedt.smartcity.xaytsccommonms.vo.Result;
import com.richstonedt.smartcity.xaytsccommonrs.common.ResultCode;
import com.richstonedt.smartcity.xaytsccommonrs.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * <b><code>GlobalExceptionHandler</code></b>
 * <p/>
 * Description
 * <p/>
 * <b>Creation Time:</b> 2021/10/20 下午8:50.
 *
 * @author Chenguidong
 * @since xaytsc-common-be
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    public Result handleConstraintViolationException(MissingServletRequestParameterException e) {
        return ResultUtil.error(e.getMessage());
    }
    /**
     * 统一处理请求参数校验(实体对象传参)
     *
     * @param e BindException
     * @return IndicatorResponse
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result validExceptionHandler(MethodArgumentNotValidException e) {
        StringBuilder message = new StringBuilder();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for (FieldError error : fieldErrors) {
            message.append(error.getField()).append(error.getDefaultMessage()).append(",");
        }
        message = new StringBuilder(message.substring(0, message.length() - 1));
        return ResultUtil.error(ResultCode.ILLEGAL_PARAMS.getCode(),message.toString());
    }

    @ExceptionHandler(value = Exception.class)
    public Result errorHandler(Exception e) {
        e.printStackTrace();
        log.info(ExceptionUtil.stacktraceToString(e));
        log.info(e.getMessage());
        return ResultUtil.error(ResultCode.FAILED.getCode(), ResultCode.FAILED.getMessage());
    }

}
